import React, { useRef } from'react';
import html2canvas from 'html2canvas';
import {Button} from 'antd'
function ScreenshotComponent() {
    // 使用useRef创建一个引用，用于指向需要截图的元素
    const captureRef = useRef(null);
    // 定义截图按钮的点击事件处理函数
    const handleCaptureClick = () => {
        const element = captureRef.current;
        // console.log('element',element)

        if (element) {
            // 使用html2canvas将元素转换为canvas
            html2canvas(element).then(canvas => {
                const imgData = canvas.toDataURL('image/png');
                // 创建一个隐藏的链接元素
                const link = document.createElement('a');
                link.href = imgData;
                // 设置下载文件名
                link.download ='screenshot.png';
                // 触发点击事件，下载截图
                link.click();
            });
        }
    };

    return (
        <div>
            {/* 包含需要截图内容的元素，并将其引用传递给captureRef */}
            <div ref={captureRef} style={{ padding: '10px', border: '1px solid #000',width:400 }}>
                <h1>Hello, World!</h1>
                <p>This content will be captured as an image.</p>
            </div>
            {/* 截图按钮 */}
            <Button onClick={handleCaptureClick} style={{marginTop:12}}>捕捉屏幕截图</Button>
        </div>
    );
}

export default ScreenshotComponent;